<template>
  <div
    id="resourceSum"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
  >
    <el-card class="box-card">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="部门人员投入工时清单" name="first">
          <el-row>
            <el-col :xs="24" :sm="12" :lg="12" class="col-box">
            <span class="col-span">部门：</span>
            <el-cascader style="width:30%"  @change="changeFilter"  :options="departmentFilterData"
            :props="{ multiple: true }" collapse-tags clearable ></el-cascader>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="12" class="col-box">
                <span class="col-span">技术领域：</span>
                <el-cascader
                style="width: 30%"
                    :options="singleFilterData"
                    :props="{ multiple: true }"
                    @change="changeFilter1"
                    collapse-tags
                    clearable></el-cascader>
            </el-col>
            <el-col :xs="24" :sm="8" :lg="8" class="col-box">
              <span class="col-span">时间段：</span>
              <el-date-picker
                  v-model="dateRange"
                  @change="changeDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
              </el-date-picker>
            </el-col>
          </el-row>
          <div>
            <!-- <div style="display: inline-block"><div style="width:30px;height:20px;background:#feecbade;display: inline-block;margin-top:10px"></div> <span style="font-size:14px;font-weight:normal">未分配满</span></div>
            <div style="display: inline-block"><div style="width:30px;height:20px;background:#eb070763;display: inline-block;margin-top:10px"></div> <span style="font-size:14px;font-weight:normal">未投</span></div> -->
            <el-button type="warning" round style="float: right;margin-bottom:10px;" @click="down">导出</el-button>
              <el-table
                :key="Math.random()"
                ref="singleTable"
                :data="tableData"
                border
                style="width: 100%;margin-bottom:10px"
                min-height='300'
                :header-cell-style="{ background: '#eef1f6',height: '60px'}"
              >
              <!-- :cell-class-name="addClass" -->
                <el-table-column label="姓名" width="130" align="center" fixed="left">
                    <template slot-scope="scope">
                        {{ scope.row.user}}
                    </template>
                </el-table-column>
                <el-table-column label="员工类型" width="100" align="center" fixed="left">
                    <template slot-scope="scope">
                        {{ scope.row.type}}
                    </template>
                </el-table-column>
                <el-table-column label="一级部门" width="180" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.dept1_name}}
                    </template>
                </el-table-column>
                <el-table-column label="二级部门"  width="180" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.dept2_name}}
                    </template>
                </el-table-column>

                <el-table-column label="项目名" align="center" width="180">
                    <template slot-scope="scope">
                      <div v-if="scope.row.project_list.length == 0">
                        {{ "-" }}
                      </div>
                      <div v-for="(v,i) in scope.row.project_list" :key="i" v-else>
                          <div v-if="scope.row.project_list.length > 1">
                              <div v-if="i != scope.row.project_list.length-1" class="borders"> {{ v }} </div>
                              <div v-else-if="i == scope.row.project_list.length-1" style="margin-top:10px;margin-bottom:10px"> {{ v }} </div>
                              <div v-else> {{ v }}  </div>
                          </div>
                          <div v-else>{{ v }}</div>
                      </div>
                    </template>
                </el-table-column>
                <el-table-column label="技术领域" align="center" width="180">
                    <template slot-scope="scope">
                      <div v-if="scope.row.technical_field_names.length == 0">
                        {{ "-" }}
                      </div>
                      <div v-else>
                          <el-tooltip placement="top" effect="light">
                              <div slot="content"  >
                                <div style="line-height: 20px" v-for="(v,i) in scope.row.technical_field_names" :key="i">{{v}}</div>
                              </div>
                                <el-tag type="primary" style="margin-top:3px" v-for="(v,i) in scope.row.technical_field_names" :key="i">{{v.length > 8 ? v.substring(0,13) + '...' : v+ '...' }}</el-tag> <!--{{v.length > 8 ? v.substring(0,13) + '...' : v }}-->
                            </el-tooltip>
                      </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" v-for="(val,i) in weekList" :key="i" :prop="val" :label="week2date(val)" width="180">
                    <template slot-scope="scope">
                      <div v-if="scope.row.week_spend[val]">
                        {{ scope.row.week_spend[val].toFixed(1) }}
                      </div>
                    </template>
                </el-table-column>
              </el-table>
           
            <el-pagination 
            v-show="tableTotal > 10" 
            background 
            layout="prev, pager, next" 
            :page-size="params.pageSize" 
            @size-change="pageSizeChange" 
            @current-change="pageNoChange" 
            :current-page="params.pageNo" 
            style="text-align: center" 
            :total="tableTotal">
          </el-pagination>
          </div>
        </el-tab-pane>
        <el-tab-pane label="部门列表" name="second">
          <el-row>
            <el-col :xs="24" :sm="12" :lg="12" class="col-box">
              <span class="col-span">需求部门：</span>
               <el-select 
               style="width:40%" 
               v-model="selectedDep" 
               placeholder="请选择" 
               @change="recouseDeptFilterFn"
               clearable
               collapse-tags
               multiple
               filterable
               >
                <el-option
                  v-for="(v,i) in recouseDeptData"
                  :key="i"
                  :label="v.name"
                  :value="v.id">
                </el-option>
              </el-select>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="12" class="col-box">
              <span class="col-span">技术领域：</span>
              <el-cascader
              style="width: 30%"
                  ref="tree"
                  :options="singleFilterData"
                  :props="{ multiple: true }"
                  @change="changeFilter2"
                  collapse-tags
                  clearable
                  filterable></el-cascader>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="12" class="col-box">
              <span class="col-span">实施部门：</span>
              <el-select 
               style="width:40%" 
               v-model="selectedDep1" 
               placeholder="请选择" 
               @change="needDeptFilterFn"
               clearable
               collapse-tags
               multiple
               filterable
               >
                <el-option
                  v-for="(v,i) in needDeptData"
                  :key="i"
                  :label="v.label"
                  :value="v.value">
                </el-option>
              </el-select>
            </el-col>
            <el-col :xs="24" :sm="8" :lg="8" class="col-box">
                  <span class="col-span">时间段：</span>
                  <el-date-picker
                      v-model="dateRange1"
                      @change="changeDateRange1"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期">
                  </el-date-picker>
                </el-col>

                <el-button type="warning" round style="float: right;" @click="down1">导出</el-button>
          </el-row>
          
            <el-table
              :key="Math.random()"
              :data="tableData1"
              border
              style="width: 100%"
              min-height='300'
              :header-cell-style="{ background: '#eef1f6',height: '60px'}">
              <el-table-column label="部门名称" width="180" align="center">
                <template slot-scope="scope">
                  {{ scope.row.dept_name}}
                </template>
              </el-table-column>
              <el-table-column label="技术领域" align="center" width="200">
                <template slot-scope="scope">
                    <div v-for="(k,i) in scope.row.dept_technical_field" :key='i'>
                      <el-tooltip effect="light">
                        <div slot="content">{{k.technical_field_name }}</div>
                        <div class="borders2" style="line-height: 215px;">
                          {{ k.technical_field_name.length > 15 ? k.technical_field_name.substring(0,14)+'...':k.technical_field_name }}
                        </div>
                      </el-tooltip>
                    </div>
                </template>
              </el-table-column>
              <el-table-column label="分类" width="180" align="center">
                <template slot-scope="scope">
                <div v-for="(k,i) in scope.row.dept_technical_field" :key='i'>
                  <div class="borders2">
                    <div class="borders3">{{ '项目总需求' }}</div>
                    <div class="borders3">{{ '人员已分配' }}</div>
                    <div class="borders3">{{ '人员未分配' }}</div>
                    <div class="borders3">{{ '项目未满足率（%）' }}</div>
                  </div>
                </div>
                </template>
              </el-table-column>
              <el-table-column align="center" v-for="(val,i) in weekList1" :key="i" :prop="val" :label="week2date(val)" width="180">
                    <template slot-scope="scope">
                      <div v-if="scope.row.dept_technical_field.length!=0">
                        <div v-for="(key,i1) in scope.row.dept_technical_field" :key='i1'>
                            <div class="borders3">{{ key.value[val].aggregate_demand.toFixed(1)}}</div>
                            <div class="borders3">{{ key.value[val].allocated.toFixed(1) }}</div>
                            <div class="borders3">{{ key.value[val].unallocated.toFixed(1) }}</div>
                            <div class="borders3">{{ key.value[val].unsatisfied}}</div>
                        </div>
                      </div>
                      <div v-else>
                        <span>{{'-'}}</span>        
                      </div>  
                    </template>
                </el-table-column>
            </el-table>
          
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { getHeaderName } from '@/app.config'
import Cookies from 'js-cookie';
import VTitle from '@/views/sys/internetThings/title';
import { mapState, mapMutations } from 'vuex';
import http from '@/views/sys/axios';
import { Loading } from 'element-ui';
import { DateUtil } from './utils.js'

export default {
  name: 'resourceSum',
  components: {
    VTitle,
  },
  data() {
    return {
      needDeptData:[],
      selectedDep1:'',
      dateRange: [],
      dateRange1: [],
      deptNames:[],
      params1:{},
      weekList1:[],
      selectedDep:'',
      recouseDeptData:[],
      tableData1:[],
      activeName: 'first',
      technical_field:[],
      departments:[],
      tableTotal: 0,
      paramData:{},
      singleFilterData: [],
      params:{
        pageNo: 1,
        pageSize: 13
      },
      weekList: [],
      loading: false,
      tableData: [],
      departmentFilterData:[],
    };
  },
  computed: {
    // tableData1: function () {
    //   return this.dept_technical_field.filter(function (user) {
    //   return user.dept_technical_field.length>0
    //   })
    // }
  },
  created(){
    this.defaultWeekTime()
    Promise.all([this.getDepartmentOwn(),this.getProjectTree()]).then((res) => {
      let data1 = res[0].data.data
      this.dept_word = data1.dept_name
      this.params['department'] = data1
      this.getDepartmentFilter()
    //   this.getDataList()
    })
  },
  mounted(){
      this.gettableData()
      this.getSingleFilter()
      this.recouseDeptFilter()
      this.gettableData1()
      this.needDeptOptions()
  },
  watch:{},
  methods: {
    defaultWeekTime() {
      let startD = new Date()
      let endD = new Date()
      endD.setMonth(endD.getMonth() + 1)
      let beginDate = startD.getFullYear()+'-'+(startD.getMonth()+1)+'-'+startD.getDate()
      let endDate = endD.getFullYear()+'-'+(endD.getMonth()+1)+'-'+endD.getDate()
      this.dateRange = [beginDate,endDate]
      this.dateRange1 = [beginDate,endDate]
      this.weekList = DateUtil.estLabourWeek(beginDate,endDate)
      this.weekList1 = DateUtil.estLabourWeek(beginDate,endDate)
      console.log(this.weekList1)
    },
    down1(){
      this.loading = true
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/resources_statistics_info_to_excel',
        method: "get",
        headers: getHeaderName(),
        responseType: 'blob',
      }).then(res => {
        if(res.status === 200) {
          const blob = new Blob([res.data]);
          const fileName = '资源看板-资源维度部门列表.xls';
          // for IE
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName)
        } else {
            // for Non-IE (chrome, firefox etc.)
            const elink = document.createElement('a');
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href);
            document.body.removeChild(elink);
            this.$message({
              type:"success",
              message:"导出成功!"
            })
            this.loading = false
        }
        } else {
          this.loading = false
          // this.$message.error('下载出错了!'); 
        }
      }).catch(err => {
          // this.$message.error('下载出错了!'); 
          this.loading = false
      })
    },
    changeDateRange(e) {
      let list = []
      if(e) {
        list = DateUtil.estLabourWeek(e[0],e[1])
      }
      // this.pramData.pageNo = 1
      this.weekList = list
      this.gettableData()
    },
    changeDateRange1(e) {
      let list = []
      if(e) {
        list = DateUtil.estLabourWeek(e[0],e[1])
      }
      // this.pramData1.pageNo = 1
      this.weekList1 = list
      this.gettableData1()
    },
    changeFilter2(e){
      let tempArr = this.$refs.tree.getCheckedNodes() //取父节点
      let technical_field1 = []
      tempArr.map(val => {
        technical_field1.push(val.value)
      })
      this.params1['technical_field'] = technical_field1
      this.gettableData1()
    },
    needDeptFilterFn(e){
      this.params1['demand_dept_names'] = e
      this.gettableData1()
    },
    needDeptOptions(){
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/resources_statistics/list ',
        methods: "get",
        headers: getHeaderName(),
      }).then((res => {
        if (res.data.code === 200) {
            this.needDeptData = res.data.data
        }
      }))
    },
    recouseDeptFilterFn(e){
      let tempArr=[]
      this.recouseDeptData.forEach(item=>{
        if(e.indexOf(item.id)>-1){
          tempArr.push(item.name)
        }
      })
      this.params1['dept_names'] = tempArr
      this.gettableData1()
    },
    recouseDeptFilter(){
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/department/list',
        methods: "get",
        headers: getHeaderName(),
        params: {
            type: 'own'
        }
      }).then((res => {
        this.recouseDeptData = res.data.data
      }))
    },
    gettableData1(){
      this.loading = true
      this.params1['week_range'] = this.weekList1.join()
      this.$axios({
            url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/resources_statistics_info',
            method: "post",
            headers: getHeaderName(),
            data:this.params1
        }).then((res => {
          if(res.data.code === 200){
            this.loading = false
            this.tableData1 = res.data.data.data
          }
        }))
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    down(res, name) {
      this.loading = true
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/resources_user_info_to_excel',
        method: "get",
        headers: getHeaderName(),
        responseType: 'blob',
      }).then(res => {
        if(res.status === 200) {
          const blob = new Blob([res.data]);
          const fileName = '资源看板-资源维度人员列表.xls';
          // for IE
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName)
            this.$message.succsee("导出成功!")  
        } else {
            // for Non-IE (chrome, firefox etc.)
            const elink = document.createElement('a');
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href);
            document.body.removeChild(elink);
            this.loading = false
            this.$message({
              type:"success",
              message:"导出成功!"
            })
        }
        } else {
          this.loading = false
          this.$message.error('下载出错了!'); 
        }
      }).catch(err => {
          this.$message.error('下载出错了!'); 
          this.loading = false
      })
    },
    addClass({row, column, rowIndex, columnIndex}){
      if(columnIndex > 5) {
        let spendTime = 0
          if(row.week_spend[column.property]){
                spendTime = Number(row.week_spend[column.property])
              if(spendTime < 1 && spendTime > 0){
                return 'cell-one'
              }
              if(spendTime == 1){
                return ''
              }
          }else{
            return 'cell-zore'
          }
      }
    },
    pageNoChange(val) {
      this.params.pageNo = val
      this.gettableData()
    },
    pageSizeChange(val) {
      this.params.pageSize = val
      this.gettableData()
    },
    week2date(val) {
        let arr = val.split("-")
        let year = arr[0]
        let week = arr[1]

        let betDay = new Date(year+1+'-01-01 00:00:00').getTime() - new Date(year+'-01-01 00:00:00').getTime()
        let newD1 = new Date(year,0,1)
        let newD2 = new Date(year,11,31)
        
        let dayMS=24*60*60*1000
        let firstDay=firstDay=(7-newD1.getDay())*dayMS
        let weekMS=0
        if(newD1.getDay() < 4) {
            weekMS=(week-2)*7*dayMS
        } else {
            weekMS=(week-1)*7*dayMS
        }
        let result=newD1.getTime()+firstDay+weekMS+5*dayMS
        newD1.setTime(result)
        return val + '周\n(' + newD1.getFullYear() + "/" + (newD1.getMonth()+1) + "/" +newD1.getDate() + ')'
    },
    gettableData(){
      this.loading = true
      this.params['week_range'] = this.weekList.join()
      this.params['department'] = this.departments
      this.params['technical_field'] = this.technical_field
      this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/resources_user_info',
          method: "post",
          headers: getHeaderName(),
          data:this.params
      }).then(res => {
          if(res.data.code === 200){
              this.loading = false
              this.tableData = res.data.data.data
              this.tableTotal = res.data.data.totalCount
          }
      })
    },
    getSingleFilter() {
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/filter/technical_field/tree',
        method: "get",
        headers: getHeaderName(),
      }).then(res => {
        this.singleFilterData = res.data.data
      })
    },
    getProjectTree() {},
    getDepartmentOwn() {
      return new Promise((resolve, reject) => {
        this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/department/own',
          method: "get",
          headers: getHeaderName(),
        }).then(res => {
          resolve(res)
          
        }).catch(error => {
            reject(error)
        })
      })
      
    },
    tableRowClassName({row, rowIndex}) {
        if (rowIndex%2 === 0) {
            return 'warning-row';
        } 
        return '';
    },
    getDepartmentFilter() {
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/department/tree',
        method: "get",
        headers: getHeaderName(),
      }).then(res => {
        this.departmentFilterData = res.data.data.tree_data
      }).catch(error => {
      })
    },
    changeFilter(val){
      this.departments = []
      val.map(item => {
        this.departments.push(item[item.length-1])
      })
      this.params.pageNo = 1
      this.params.pageSize = 13
      this.gettableData()
    },
    changeFilter1(e){
      this.technical_field = []
      e.map(item => {
        this.technical_field.push(item[item.length-1])
      })
      this.params.pageNo = 1
      this.params.pageSize = 13
      this.gettableData()
    },
  },

};
</script>

<style lang="scss" scoped>
// th.gutter{
//   width:  23px !important;
//   display: block !important;
// }
/deep/ .el-table td.cell-one { 
  background-color:#feecbade  !important;
  color: #82848a;
}
/deep/ .el-table td.cell-zore { 
  background-color:#eb070763 !important;
  color: #82848a;
}
/deep/.el-table .warning-row {
    background: oldlace;
  }
/deep/.el-table--enable-row-transition .el-table__body td {
  padding: 0px;
  height: 43px
}
.col-box {
  display: flex;
  margin-bottom: 10px;
  .col-span {
    min-width: 100px;
    line-height: 36px;
  }
}
.borders3{
  border-bottom: 1px solid #c5c4c1;
  height: 35px;
  width: 203px;
  margin-left: -14px;
  margin-top:10px
}
.borders2{
  border-bottom: 1px solid #c5c4c1;
  height: 170px;
  width: 203px;
  margin-left: -14px;
  margin-top:10px
}
.borders1{
  border-bottom: 1px solid #c5c4c1;
  height: 27px;
  width: 183px;
  margin-left: -14px;
//   margin-top:10px;
  // margin-bottom:10px;
}
.borders{
  border-bottom: 1px solid #c5c4c1;
  height: 27px;
  width: 183px;
  margin-left: -14px;
  margin-top:10px;
  // margin-bottom:10px;
}
#resourceSum {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;
  //   .btn-group {
  //     position: relative;
  //     .edit {
  //       position: absolute;
  //       top: 50%;
  //       right: -2%;
  //       transform: translate(-50%, -50%);
  //     }
  //   }
}
</style>